package com.magic.smartcity.view.more.bus

import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.snackbar.Snackbar
import com.magic.smartcity.R
import com.magic.smartcity.databinding.FragmentBusHomeBinding
import com.magic.smartcity.utils.Constant
import com.magic.smartcity.view.more.adapters.BusLineListAdapter
import com.magic.smartcity.view.more.viewmodels.BusViewModel

class BusHomeFragment : Fragment() {

    private lateinit var binding: FragmentBusHomeBinding
    private val busLineListAdapter = BusLineListAdapter()

    private val viewModel by lazy {
        ViewModelProvider(this).get(BusViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.getLineList()
        viewModel.getLineStationList()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentBusHomeBinding.inflate(layoutInflater)
        setHasOptionsMenu(true)
        initView()
        return binding.root
    }

    private fun initView() {
        //初始化巴士线路
        binding.busHomeRy.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        binding.busHomeRy.adapter = busLineListAdapter
        viewModel.busLineList.observe(viewLifecycleOwner) { busLineList ->
            viewModel.busLineStationList.observe(viewLifecycleOwner) { busLineStation ->
                busLineListAdapter.setData(busLineList, busLineStation)
            }
        }

    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.bus_home, menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.bus_home_myOrder) {
            if (Constant.TOKEN != null)
                Navigation.findNavController(binding.root)
                    .navigate(R.id.action_busHomeFragment_to_busOrderFragment)
            else{
                val notLogin = Snackbar.make(binding.root, "未登录", Snackbar.LENGTH_SHORT)
                notLogin.setAction("去登陆"){ v->
                    Navigation.findNavController(binding.root).navigate(R.id.loginFragment)
                }.show()
            }
        }
        return super.onOptionsItemSelected(item)
    }
}